package com.ityxh.common.GlobalException;

import com.ityxh.common.returns.R;
import com.ityxh.common.exception.IdempotentException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@Slf4j
//把错误信息转换成JSON
@ResponseBody
public class GlobalExceptionHandler {


    @ExceptionHandler(IdempotentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleIdempotentException(IdempotentException ex) {
        // 根据需要自定义错误消息
        String errorMessage = ex.getMessage();
        return R.failed()
                .setMsg(errorMessage)
                .setCode(400);
    }



    /**
     * 全局异常.
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleGlobalException(Exception e) {
        log.error("全局异常信息 ex={}", e.getMessage(), e);
        return R.failed(e.getLocalizedMessage());
    }
}
